package com.fxb.learn.learn_rate_limiter.demo01;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * @author wangxiyue@cyou-inc.com
 * @date 2020-01-09
 * @since 1.0.0
 */
@Component
public class RedisRateLimiter {

    private StringRedisTemplate redisTemplate;

    public boolean rateLimit(String key,int max, int rate){
        ArrayList<String> keys = new ArrayList<>();
        keys.add(key);
        return "1".equals(
                redisTemplate.execute(new RedisRateLimitScript(),
                        keys, Integer.toString(max),Integer.toString(rate),
                Long.toString(System.currentTimeMillis()))
        );
    }

    @Autowired
    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
}
